package com.yilin.tms.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.StringUtil;
import com.yilin.tms.core.entity.data.document.Document;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.data.mapper.DocumentMapper;
import com.yilin.tms.data.service.IDocumentResourceService;
import com.yilin.tms.data.service.IDocumentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 帮助文档目录服务
 *
 * @author zhangjinyuan
 * @date 2023/08/07  11:06
 */
@Service
public class DocumentService extends ServiceImpl<DocumentMapper, Document> implements IDocumentService {

    @Resource
    private IDocumentResourceService resourceService;

    /**
     * 添加帮助文档
     */
    @Override
    @Transactional
    public void addDocument(Account loginUser, Document document) {
        Document parent = getById(document.getParentId());
        if (parent.getType()) {
            throw new RuntimeException("父节点不能是资源节点");
        }
        document.setAddUserId(loginUser.getAddUserId());
        document.setCreateTime(document.getCreateTime());
        save(document);
    }

    /**
     * 删除帮助文档
     */
    @Override
    @Transactional
    public void deleteDocument(String documentId) {
        List<Document> childrenList = list(new QueryWrapper<Document>().eq("parent_id", documentId));
        if (ArrayUtil.isNotEmpty(childrenList)) {
            Document children = childrenList.get(0);
            Document parent = getById(children.getParentId());
            throw new RuntimeException(String.format("%s存在子文档无法请先删除子文档", parent.getName()));
        }
        Document document = getById(documentId);
        if (document.getType() && StringUtil.isNotEmpty(document.getResourceId())) {
            resourceService.removeById(document.getResourceId());
        }
        removeById(documentId);
    }

    /**
     * 修改帮助文档
     */
    @Override
    @Transactional
    public void editDocument(Account loginUser, Document document) {
        Document local = getById(document.getId());
        if (!Objects.equals(local.getParentId(), document.getParentId())) {
            throw new RuntimeException("帮助文档不可变更父目录");
        }
        document.setUpdateUserId(loginUser.getId());
        document.setUpdateTime(new Date());
        updateById(document);
    }
}
